<!--
 * @Author: 赵京涛 z19472333952022@163.com
 * @Date: 2024-07-13 21:53:37
 * @LastEditors: 赵京涛 z19472333952022@163.com
 * @LastEditTime: 2024-07-13 21:53:37
 * @projectName: data_analysis_web
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" v-loading="loading.bodyLoading">
    <el-form ref="searchForm" :inline="true" :model="form" size="small" v-loading='loading.loading2'>
      <el-form-item v-for="field in searchFromDataList" :key="field.fieldCode" :label="field.fieldName">
        <!-- text格式为默认为模糊查询-->
        <template v-if="field.type === 'text'">
          <el-input v-model="form[field.fieldCode]" clearable :placeholder="'请输入' + field.fieldName" />
        </template>
        <template v-else-if="field.type === 'date'">
          <el-date-picker v-model="form[field.fieldCode]" type="date" placeholder="选择日期" :default-value="field.defaultValue" value-format="yyyy-MM-dd" />
        </template>
        <template v-else-if="field.type === 'date_year'">
          <el-date-picker v-model="form[field.fieldCode]" type="year" :default-value="field.defaultValue" placeholder="选择年份" value-format="yyyy" />
        </template>
        <template v-else-if="field.type === 'dateTime'">
          <el-date-picker v-model="form[field.fieldCode]" type="datetime" :default-value="field.defaultValue" placeholder="选择日期时间" align="right"
            value-format="yyyy-MM-dd HH-mm-ss" />
        </template>
        <!-- 一般下拉框 -->
        <template v-else-if="field.type === 'select_key'">
          <el-select v-model="form[field.fieldCode]" :placeholder="'请选择' + field.fieldName" clearable>
            <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </template>
        <!-- 下拉框（多级） -->
        <template v-else-if="field.type === 'select'">
          <el-select v-model="form[field.fieldCode]" :placeholder="'请选择' + field.fieldName" clearable>
            <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </template>
        <!-- 检索下拉框 -->
        <template v-else-if="field.type === 'select_text'">
          <el-select v-model="form[field.fieldCode]" :placeholder="'请选择' + field.fieldName" filterable clearable>
            <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item>
        <lv-button v-show="searchFromDataList && searchFromDataList.length > 0" type="p" size="small" label="查询" icon="el-icon-search" @click="searchHandler" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <lv-button v-hasPermi="['monitor:job:edit']" label="数据导出" type="d" size="small" icon="el-icon-download" @click="downloadDataHandler" msg="是否确认将数据导出?" />
      </el-col>
    </el-row>
    <el-table v-loading="loading.loading1" :data="tableList" @sort-change="handleSortChangeHandler" border>
      <el-table-column align="center" width="80px" label="序号">
        <template v-slot:default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <template v-for="(item, index) in headerList">
        <!-- 重写Id -->
        <el-table-column v-if="item.label === 'ID'" :key="index" align="center" width="80px" :label="item.label" :fixed="item.fixed">
          <template v-slot:default="scope">
            {{ scope.row["id"] }}
          </template>
        </el-table-column>
        <!-- 重写点位类型 -->
        <el-table-column v-else-if="item.label === '点位类型'" :key="index + 'dwlx'" align="center" width="130px" :label="item.label" :fixed="item.fixed">
          <template v-slot:default="scope">
            {{ scope.row["dwlx"] }}
          </template>
        </el-table-column>
        <!-- 重写序号 -->
        <el-table-column v-else-if="item.label === '序号'" :key="index + 'xh'" align="center" :width="item.width" :label="item.label" :fixed="item.fixed">
          <template v-slot:default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <!-- 针对于简单行表头数据 -->
        <el-table-column v-else-if="!item.rowspan && !isShowThreeColumn" :key="index + item.key" align="center" :width="item.width" :prop="item.key"
          :label="item.label" sortable="custom">
          <template v-slot:default="scope">
            <span>{{ scope.row[item.key] }}</span>
          </template>
        </el-table-column>
        <!-- 针对于item.label并且是复杂表头（二级表头）的情况 -->
        <el-table-column v-else-if="item.rowspan && item.label !== ''" :key="item.key + '_index'" :label="item.label"
          :width="item.key === 'data_name' ? '150px' : (item.key === 'jcrq' || item.key === 'qy_xbzs' || item.key === 'jcsd' || item.key === 'jczw' || item.key === 'xbzs' ? '160px' : item.key === 'exceedance_factor' || item.key === 'wzzs' ? '110px' : item.key === 'czwzxbsl' || item.key === 'ccjzmd' || item.key === 'ccjzndbs' ? '200px': '')"
          align="center" :prop="item.key" :fixed="item.fixedColumn === 'left' || item.fixedColumn === 'right' ? item.fixedColumn : false" sortable="custom">
          <template v-slot:default="scope">
            <span style="width: 100%; height: 100%; display: block"
              :style="{ backgroundColor: scope.row[`${item.key}_CellColor`] ? scope.row[`${item.key}_CellColor`] : 'inherit', color: scope.row[`${item.key}_CellColor`] ? 'white' : 'black'}">{{ scope.row[item.key] }}</span>
          </template>
        </el-table-column>
        <!-- 针对于一级统计分析列表（二级表头） -->
        <el-table-column v-else-if="item.columnName !== '' && item.category !== '' && item.columnName !== item.category && !isShowThreeColumn"
          :key="item.key + item.key + '_index'" align="center" :label="item.columnName">
          <template v-if="!item.list">
            <el-table-column :key="item.key" align="center" :prop="item.key" :label="item.category"
              :width="item.key === 'czwzxbsl' || item.key === 'ccjzmd' || item.key === 'ccjzndbs' ? '300px' : ''" sortable="custom">
              <template v-slot:default="scope">
                <span style="width: 100%; height: 100%; display: block"
                  :style="{ backgroundColor: scope.row[`${item.key}_CellColor`] ? scope.row[`${item.key}_CellColor`] : 'inherit', color: scope.row[`${item.key}_CellColor`] ? 'white' : 'black'}">{{ scope.row[item.key] }}</span>
              </template>
            </el-table-column>
          </template>
          <!-- 单日极值 累计极值 -->
          <template v-if="item.list">
            <el-table-column v-for="itemList in item.list" :key="itemList.key" align="center" :prop="itemList.key" :label="itemList.category" sortable="custom"
              :width="itemList.category === '超出基准浓度倍数（倍）' || itemList.category === '赤潮基准密度（cells/L）' || itemList.category === '平均细胞密度（cells/L）' || itemList.category === '最大值点位' || itemList.category === '最小值点位' || itemList.category === '中位数点位' ? '200px' : itemList.key === 'czwzxbsl' || itemList.key === 'ccjzmd' ? '220px' : ''">
              <template v-slot:default="scope">
                <span style="width: 100%; height: 100%; display: block"
                  :style="{ backgroundColor: scope.row[`${itemList.key}_CellColor`] ? scope.row[`${itemList.key}_CellColor`] : 'inherit', color: scope.row[`${itemList.key}_CellColor`] ? 'white' : 'black'}">{{ scope.row[itemList.key] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <!-- 针对于数据统计 => 三级表头 -->
        <el-table-column v-if="item.columnName !== '' && item.category !== '' && item.columnName !== item.category && isShowThreeColumn" :key="item.columnName"
          align="center" :label="item.columnName">
          <template v-if="item.list">
            <el-table-column v-for="itemList in item.list" :key="itemList.category" align="center" :label="itemList.category" width="150px"
              :prop="itemList.list.length <= 1 ? itemList.list[0].key : undefined">
              <template v-if="itemList.list.length > 1">
                <el-table-column v-for="itemThree in itemList.list" :key="itemThree.key" align="center"
                  :width="itemThree.headerThirdRow === '点位' || itemThree.headerThirdRow === '监测值' ? '220px' : ''" :prop="itemThree.key"
                  :label="itemThree.headerThirdRow" :sortable="'custom'" sortable="custom">
                  <template v-slot:default="scope">
                    <span style="width: 100%; height: 100%; display: block"
                      :style="{ backgroundColor: scope.row[`${itemThree.key}_CellColor`] ? scope.row[`${itemThree.key}_CellColor`] : 'inherit', color: scope.row[`${itemThree.key}_CellColor`] ? 'white' : 'black' }">{{ scope.row[itemThree.key] }}</span>
                  </template>
                </el-table-column>
              </template>
              <template v-slot:default="scope">
                <span style="width: 100%; height: 100%; display: block"
                  :style="{ backgroundColor: scope.row[`${itemList.list[0].key}_CellColor`] ? scope.row[`${itemList.list[0].key}_CellColor`] : 'inherit', color: scope.row[`${itemList.list[0].key}_CellColor`] ? 'white' : 'black' }">
                  {{ scope.row[itemList.list[0].key] }}
                </span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getTableDataList" />
  </div>
</template>
<script>
import LvButton from '@/components/lvButton/index.vue'
import {
  columnNameTransformArrayAccording,
  convertObjectToNewStructure,
  filterEmpty,
  findIndexInArray,
  getIsPortIsOneDisposeDataStructure,
  sortDataBySortField,
  threeColumnNameTransformDataStructure,
  transformOrder,
  useTaskSuccessHeaderTable,
  useTaskSuccesTableDataList
} from '@/hooks'
import { getDataList } from '@/api/dataSearch'
import { getIsPortIsOneList, getParameterList } from '@/api/dataReport'

export default {
  components: { LvButton },
  id: 'dataReport',
  data() {
    return {
      dataId: 0,
      pageName: '',
      total: 0,
      loading: {
        loading1: false,
        loading2: false,
        bodyLoading: false
      },
      isShowThreeColumn: false, // 是否显示三级表头数据
      headerList: [], // 动态表头
      parameterParams: '', // 查询条件集合（json）
      tableList: [],
      queryParams: {   // 查询参数
        pageNum: 1,
        pageSize: 10,
        parameter: '',
        relationId: null
      },
      listApiUrl: '', // 列表接口地址
      chartApiUrl: '', // 图表接口地址
      form: {}, // 搜索表单
      searchFromDataList: [], // 搜索表单列表数据
    }
  },
  created() {
    this.$nextTick(() => {
      this.getInit()
    })
  },
  methods: {
    // 初始化获取menuCode
    getInit() {
      const _targetApiUrl = JSON.parse(this.$route.meta.apiUrl)
      this.dataId = this.$route.query.id
      this.pageName = this.$route.meta.title
      this.listApiUrl = _targetApiUrl ? _targetApiUrl.list : ''
      this.chartApiUrl = _targetApiUrl ? _targetApiUrl.chart : ''
      this.getSearchListHandler()
    },
    // 获取查询条件数据
    async getSearchListHandler() {
      try {
        this.loading.loading2 = true
        const { code, data } = await getParameterList({ relationId: Number(this.dataId) })
        if (code === 200 && data) {
          this.searchFromDataList = sortDataBySortField(data)
          await this.isExitIsPortHandler(this.searchFromDataList)
          await this.getTableDataList()
        }
        this.loading.loading2 = false
      } catch (err) {
        console.log(err)
      }
    },
    // 列表数据
    async getTableDataList() {
      try {
        this.loading.loading1 = true
        this.queryParams.parameter = this.parameterParams
        this.queryParams.relationId = this.dataId
        const { code, data } = await getDataList(this.listApiUrl, { ...this.queryParams })
        if (code === 200 && data) {
          this.total = data.total
          // 配置表头
          const _middleHeader = useTaskSuccessHeaderTable(data.headerList)
          const isThreeColumn = _middleHeader.some(item => item.headerThirdRow)
          _middleHeader.forEach(item => {
            if (!item.headerThirdRow) delete item.headerThirdRow
          })
          if (Array.isArray(_middleHeader) && _middleHeader[0]?.colspan && !isThreeColumn) {
            this.headerList = columnNameTransformArrayAccording(_middleHeader)
            this.headerList = transformOrder(_middleHeader, this.headerList).filter(s => s.isShow !== 0 && s.columnName !== 'id')
            this.isShowThreeColumn = false
          } else if (Array.isArray(_middleHeader) && isThreeColumn) {
            this.headerList = threeColumnNameTransformDataStructure(_middleHeader)
            this.isShowThreeColumn = true
          } else {
            this.isShowThreeColumn = false
            this.headerList = _middleHeader
          }
          // 配置表格数据
          this.tableList = useTaskSuccesTableDataList(data.list)
        } else {
          this.total = 0
          this.tableList = []
        }
        this.loading.loading1 = false
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 查询
     */
    async searchHandler() {
      const resRromEmpty = filterEmpty(JSON.parse(JSON.stringify(this.form)))
      this.parameterParams = convertObjectToNewStructure(resRromEmpty, this.searchFromDataList)
      await this.getTableDataList()
    },
    // 数据导出
    downloadDataHandler() {
      this.download('/select/getDataList_report.do', { relationId: this.dataId, parameter: this.parameterParams }, `${this.pageName}.xlsx`)
    },
    /**
     * 处理数组中的每个元素，根据元素的属性执行异步操作。
     *
     * @param {Array} arrItem 包含多个对象的数组，每个对象代表一个表单项。
     * @returns {Promise<{form: Object}>} 返回一个Promise，解析后得到更新后的表单对象。
     */
    async isExitIsPortHandler(arrItem) {
      // 如果数组为空或没有元素，则直接解析并返回当前的表单对象
      if (!arrItem || arrItem.length === 0) {
        return Promise.resolve({ form: this.form })
      }
      // 遍历数组中的每个元素，并为每个元素生成一个对应的异步操作Promise
      const promises = arrItem.map(async (item) => {
        // 如果元素的isPort属性为1，则执行特定逻辑
        if (item.isPort === 1) {
          if (!['jcrq-start', 'jcrq-end', 'jsrq-start', 'jsrq-end', 'start_date-start', 'start_date-end'].includes(item.fieldCode)) {
            // 如果fieldCode不是特定的几个值，则调用fetchOptionsHandler函数
            await this.fetchOptionsHandler(item)
          } else {
            // 对于特定的fieldCode，调用getIsPortIsOneList函数并更新表单值
            const response = await getIsPortIsOneList(item.value)
            if (item.fieldCode.endsWith('-start') && (!this.form[item.fieldCode] || this.form[item.fieldCode] === '') && this.form[item.fieldCode] !== null) {
              this.$set(this.form, item.fieldCode, response.data)
            } else if (item.fieldCode.endsWith('-end') && (!this.form[item.fieldCode] || this.form[item.fieldCode] === '') && this.form[item.fieldCode] !== null) {
              this.$set(this.form, item.fieldCode, response.data)
            }
          }
        } else if (item.value && item.value !== '') {
          // 如果元素的isPort属性不为1且value属性不为空，则调用getIsValueHaveHandler函数
          await this.getIsValueHaveHandler(item)
        }
      })
      // 等待所有的异步操作完成
      await Promise.all(promises)
      // 返回更新后的表单对象
      return { form: this.form }
    },
    /**
     * 如果说isPort的参数为1 就需要请求接口取值了
     * @param item
     * @returns {Promise<void>}
     */
    async fetchOptionsHandler(item) {
      try {
        const res = await getIsPortIsOneList(item.value)
        res.data && Array.isArray(res.data) && res.data.length > 0 ? this.searchFromDataList = getIsPortIsOneDisposeDataStructure(this, res.data, this.searchFromDataList, item.fieldName) : ''
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * value存在的情况下
     * @param item
     */
    getIsValueHaveHandler(item) {
      const optionList = []
      JSON.parse(item.value.replace(/'/g, '"')).forEach(r => { optionList.push({ label: r, value: r }) })
      const _info = this.searchFromDataList.find(g => g.fieldName === item.fieldName)
      _info.options = optionList
      const _idx = findIndexInArray(_info, this.searchFromDataList)
      this.$set(this.searchFromDataList, _idx, _info)
    },
    /**
     * 监听表格排序
     * @param prop
     * @param order
     */
    async handleSortChangeHandler({ prop, order }) {
      let parseParamsArr // 深拷贝一份查询参数
      if (this.parameterParams !== '') {
        parseParamsArr = JSON.stringify((JSON.parse(this.parameterParams)).filter(field => field.type !== 'order'))
      } else {
        parseParamsArr = JSON.stringify([])
      }
      const _sortObj = { ascending: 'asc', descending: 'desc', null: null }
      let sortType = null
      for (const keys in _sortObj) {
        if (order && order === keys) sortType = _sortObj[keys]
      }
      const paramsArr = [{ 'fieldCode': prop, 'type': 'order', 'value': sortType }]
      let sortArr // 排序参数
      sortType ? sortArr = paramsArr : sortArr = []
      let resParseParams = parseParamsArr ? (JSON.parse(parseParamsArr)).concat(sortArr) : JSON.parse(sortArr)
      this.parameterParams = JSON.stringify(resParseParams)
      await this.getTableDataList()
    }
  }
}
</script>
